package com.nicefact.mailmonitor.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.KeyFactory;
import com.nicefact.mailmonitor.core.APP_CONSTANTS;
import com.nicefact.mailmonitor.core.AppException;
import com.nicefact.mailmonitor.entity.AppUser;
import com.nicefact.mailmonitor.service.AppAdminService;
import com.nicefact.mailmonitor.service.AppUserService;
import com.nicefact.mailmonitor.service.ContextIOService;
import com.nicefact.mailmonitor.util.GridRequestParser;
import com.nicefact.mailmonitor.vo.GridRequest;
import com.nicefact.mailmonitor.workflow.WorkflowInfo;
import com.nicefact.mailmonitor.workflow.entity.Workflow;
import com.nicefact.mailmonitor.workflow.impl.context.ImportUserContext;
import com.nicefact.mailmonitor.workflow.impl.processor.WorkflowStatusType;
import com.nicefact.mailmonitor.workflow.service.WorkflowService;

@Controller
public class AppUserController {

	@Autowired
	WorkflowService workflowService;

	@Autowired
	AppUserService appUserService;

	@Autowired
	private ContextIOService contextIOService;
	
	@Autowired
	private AppAdminService appAdminService;
	
	@Autowired private GridRequestParser gridRequestParser;

	@RequestMapping("/importFile.do")
	public void importUsers(HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws IOException, AppException {
		BlobstoreService blobstoreService = BlobstoreServiceFactory
				.getBlobstoreService();
		Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request);
		BlobKey blobKey = blobs.get("myFile").get(0);
		if (blobKey != null) {

			String email = (String) session.getAttribute(APP_CONSTANTS.USER);
			triggerImportTask(email, blobKey);
			try {
				BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);
				// System.out.println("blobInfo : " + blobInfo);
			} catch (Exception e) {
				System.out.println("error " + e.getMessage());
			}
		}
		// System.out.println("blob key : " + blobKey);

		response.sendRedirect("/index.do?msg=File Import has been scheduled");
	}

	@RequestMapping("/resource/syncAllUserMailBox.do")
	@ResponseBody
	public Boolean syncMailBox(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		for (AppUser user : appUserService.getAllUsers()) {
			if (!StringUtils.isBlank(user.getContextioId())) {
				System.out.println(contextIOService.syncUserMailBox(user.getContextioId()));
			}
		}
		System.out.println("all users sync triggered");
		return true;
	}
	
	@RequestMapping("/user/deleteUser.do")
	@ResponseBody
	public void deleteUser(@RequestParam("userKey") Long userKey) {
		AppUser appUser = appUserService.getUser(KeyFactory.createKey(AppUser.class.getSimpleName(), userKey));
		appUserService.remove(appUser);
	}
	
	@RequestMapping("/getAccounts.do")
	@ResponseBody
	public Map<String, Object> getAccounts(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		String email = (String) session.getAttribute(APP_CONSTANTS.USER);
		GridRequest dataCriteria = gridRequestParser.parseDataCriteria(request);
		 List<AppUser> appUsers = appUserService.searchUsers(dataCriteria,email);
		 
		return getModalMap(appUsers,dataCriteria,email);
	}

	private Map<String, Object> getModalMap(List<AppUser> objectList,
			GridRequest dataCriteria, String email) {
		Map<String, Object> modalMap = new HashMap<String, Object>();
		if (objectList != null) {
			ArrayList<HashMap<String, Object>> rows = new ArrayList<HashMap<String, Object>>();
			int id = 0;
			for (Iterator<AppUser> iterator = objectList.iterator(); iterator
					.hasNext();) {
				AppUser object = (AppUser) iterator.next();

				HashMap<String, Object> data = new HashMap<String, Object>();
				data.put("id", ++id);

				ArrayList<Object> row = new ArrayList<Object>();
				
				row.add(object.getEmail());
				row.add(object.getFirstName());
				row.add(object.getLastName());
				String status = "Not Active";
				if (!StringUtils.isBlank(object.getContextioId())) {
					status = "Active";
				}
				row.add(status);
				row.add(object.getKey().getId());
				data.put("cell", row);
				rows.add(data);
			}

			int page = dataCriteria.getPaginationInfo().getPageNumber();
			int recordsPerPage = dataCriteria.getPaginationInfo()
					.getRecordsPerPage();
			int totalRecords = appAdminService.get(email).getNoOfAccounts();
			modalMap.put("rows", rows);
			modalMap.put("page", page);
			modalMap.put("total",
					(int) Math.ceil(totalRecords / (recordsPerPage + 0d)));

			modalMap.put("records", totalRecords);
		}
		return modalMap;
	}

	void triggerImportTask(String adminEmail, BlobKey blobKey)
			throws AppException {
		ImportUserContext context = new ImportUserContext();
		context.setAdminEmail(adminEmail);
		context.setBlobKey(blobKey);
		WorkflowInfo workflowInfo = new WorkflowInfo("ImportUserTaskProcessor");
		workflowInfo.setIsNewWorkflow(true);

		Workflow workflow = new Workflow();
		workflow.setContext(context);
		workflow.setWorkflowName(workflowInfo.getWorkflowName());
		workflow.setWorkflowInstanceId(workflowInfo.getWorkflowInstance());
		workflow.setWorkflowStatus(WorkflowStatusType.INPROGRESS.toString());
		workflow = workflowService.createWorkflow(workflow);
		context.setWorkflowInfo(workflowInfo);
		workflowService.triggerWorkflow(workflow);
	}

	@RequestMapping("/test.do")
	@ResponseBody
	public void add() {
		AppUser appUser = new AppUser();
		appUser.setEmail("admin@mellong.com");
		appUser.setContextioId("50c773832a91e8f157000013");
		appUserService.save(appUser);
	}
}
